layui.config({
    base: 'assets/layuiadmin/' //静态资源所在路径
}).extend({
    index: 'lib/index' //主入口模块
}).use(['index', 'table', 'laytpl'], function(){
    var $ = layui.$,
        form = layui.form,
        table = layui.table;

    var channelSearchData, curr = 1, limit = 50;
    var channelCommonData = JSON.parse(sessionStorage.getItem("channelCommonData"));
    sessionStorage.removeItem("channelCommonData");
    if(channelCommonData != null && !$.isEmptyObject(channelCommonData)){
        curr = channelCommonData.page;
        limit = channelCommonData.limit;
    }

    table.render({
        elem: '#data-table',
        url: 'channel/list',
        where: getData(),
        toolbar: '#data-table-toolbar',
        title: '渠道列表',
        height: globalHeight,
        page: true,
        limit: limit,
        cols: [[
            {field: 'id', title: 'ID', width: 60, align: 'center'},
            {field: 'code', title: '编号', width: 80, align: 'center'},
            {field: 'username', title: '账号',width: 100, align: 'center'},
            {field: 'type', title: '渠道类型', width: 88, align: 'center', templet: "#typeTpl"},
            {field: 'userId', title: '用户ID', width: 94, align: 'center'},
            {field: 'registerNum', title: '注册人数', width: 88, align: 'center', templet: "#numTpl"},
            {field: 'rechagePeopleNum', title: '充值人数', width: 88, align: 'center'},
            {field: 'rechageRate', title: '充值比例', width: 88, align: 'center'},
            {field: 'rechageAmountNum', title: '充值总额', width: 88, align: 'center'},
            {field: 'first_invite_recharge_rate', title: '直接邀请的用户充值金额的奖励比例(%)', width: 160, align: 'center'},
            {field: 'first_invite_rate', title: '直接邀请的主播收入的奖励比例(%)', width: 160, align: 'center'},
            {field: 'second_invite_recharge_rate', title: '间接邀请的用户充值金额的奖励比例(%)', width: 160, align: 'center'},
            {field: 'second_invite_rate', title: '间接邀请的主播收入的奖励比例(%)', width: 160, align: 'center'},
            {field: 'first_invite_vip_rate', title: '直接邀请的用户充值会员的奖励比例(%)', width: 160, align: 'center'},
            {field: 'first_invite_user_rate', title: '直接邀请用户注册奖励的积分', width: 160, align: 'center'},
            {field: 'status', title: '状态', align: 'center', templet: "#statusTpl"},
            {field: 'createTime', title: '创建时间', width: 160, align: 'center'},
            {field: 'op', title: '操作', toolbar: '#data-table-bar', width: 190, align: 'center', templet: '#data-table-bar'}
        ]],
        parseData: function(result){
            return {
                "code": result.code, //解析接口状态
                "msg": result.msg, //解析提示文本
                "count": result.data.total, //解析数据长度
                "data": result.data.datas //解析数据列表
            };
        },
        done: function (res, curr, count){
            var c = curr;
            if(c > 1){
                curr = 1;
                table.reload('data-table', {
                    page: {
                        curr : c
                    }
                });
            }
            if(channelSearchData != null && !$.isEmptyObject(channelSearchData)){
                reloadData(channelSearchData);
            }
        }
    });

    //头工具栏事件
    table.on('toolbar(data-table)', function(obj){
        switch(obj.event){
            case 'search':
                var data =  getData();
                table.reload('data-table', {
                    url: 'channel/list',
                    where: data,
                    page: {
                        curr: 1
                    }
                });
                reloadData(data);
                break;
            case 'add':
                layer.open({
                    type: 2,
                    title: '添加新渠道',
                    offset: '10%',
                    content: 'toEditChannel',
                    area: ['600px', '600px'],
                    btn: ['确定', '取消'],
                    yes: function (index, layero) {     //确定按钮回调
                        var iframeWindow = window['layui-layer-iframe'+ index],
                            submit = layero.find('iframe').contents().find("#data-submit");

                        //监听提交
                        iframeWindow.layui.form.on('submit(data-submit)', function(data){
                            var field = data.field; //获取提交的字段
                            // 加载层
                            var load = layerLoad();

                            //提交 Ajax 成功后，静态更新表格中的数据
                            post('channel/add', field, field, function (data) {
                                layer.msg("添加成功");
                                table.reload('data-table');
                                layer.close(index); //关闭弹层
                                layer.close(load); //关闭弹层
                            });
                        });

                        submit.trigger('click');
                    }
                });
                break;
        };
    });

    //监听行工具事件
    table.on('tool(data-table)', function(obj){
        var data = obj.data;
        if(obj.event === 'edit'){
            layer.open({
                type: 2,
                title: '编辑渠道',
                offset: '10%',
                content: 'toEditChannel',
                area: ['600px', '600px'],
                btn: ['确定', '取消'],
                success: function(layero, index){   //弹窗成功后回调
                    var iframeWindow = window['layui-layer-iframe' + index];
                    $(iframeWindow.document).find('#id').val(data.id);   //传值到iframe页面
                },
                yes: function (index, layero) {     //确定按钮回调
                    var iframeWindow = window['layui-layer-iframe'+ index],
                        submit = layero.find('iframe').contents().find("#data-submit");

                    //监听提交
                    iframeWindow.layui.form.on('submit(data-submit)', function(data){
                        var field = data.field; //获取提交的字段
                        // 加载层
                        var load = layerLoad();

                        //提交 Ajax 成功后，静态更新表格中的数据
                        post('channel/edit', field, field, function (data) {
                            layer.msg("更新成功");
                            table.reload('data-table');
                            layer.close(index); //关闭弹层
                            layer.close(load); //关闭弹层
                        });
                    });

                    submit.trigger('click');
                }
            });
        }else if(obj.event == 'updateStatus'){
            var msg;
            if(data.status == 0){
                msg = '确定禁用该渠道吗？';
            }else{
                msg = '确定启用该渠道吗？'
            }
            layer.confirm(msg, {offset: '30%'}, function(index){
                // 加载层
                var load = layerLoad();
                post('channel/updateStatus', {'id': data.id}, false, function (res) {
                    obj.update({
                        status:  data.status == 0 ? 1 : 0,
                        op: 1
                    });
                    layer.close(index);
                    layer.close(load);
                    layer.msg(data.status == 0 ? '禁用成功' : '启用成功');
                });
            });
        }else if(obj.event === 'restPwd'){
            layer.confirm('确定重置该渠道用户密码（重置后默认密码为：123456）', {offset: '30%'}, function(index){
                // 加载层
                var load = layerLoad();
                post('channel/restPwd', {'id': data.id}, false, function (data) {
                    layer.msg("密码重置成功");
                    layer.close(index);
                    layer.close(load);
                });
            });
        }else if(obj.event === 'viewInvite'){
            channelSearchData = {'keyword': $('#keyword').val(), 'type': $('#type').val()};
            sessionStorage.setItem("channelSearchData", JSON.stringify(channelSearchData));
            sessionStorage.setItem("channelCommonData", JSON.stringify(getCommonData()));

            window.location.href = '/toInviteManage?hrefUrl=/toChannelManage&inviteUserId=' + data.userId;
        }
    });

    /**
     * 获取查询数据
     * @returns {{host: jQuery, online: jQuery, keyword: (*|jQuery|Array|string|undefined), status: (*|jQuery|Array|string|undefined)}}
     */
    function getData() {
        var keyword, type;
        channelSearchData = JSON.parse(sessionStorage.getItem("channelSearchData"));
        sessionStorage.removeItem("channelSearchData");
        if(channelSearchData != null && !$.isEmptyObject(channelSearchData)){
            keyword = channelSearchData.keyword;
            type = channelSearchData.type;
        }else{
            keyword = $('#keyword').val();
            type = $('#type').val();
        }

        return {keyword: keyword, type: type};
    }

    /**
     * 重新渲染数据
     * @param data
     */
    function reloadData(data) {
        $('#keyword').val(data.keyword);
        $('#type').val(data.type);
        form.render();
    }
});